package com.mrper.toastprovider

import android.content.Context
import android.widget.Toast
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugin.common.PluginRegistry.Registrar

class ToastProviderPlugin private constructor(private val registrar: Registrar) : MethodCallHandler {

    companion object {
        @JvmStatic
        fun registerWith(registrar: Registrar): Unit {
            val channel = MethodChannel(registrar.messenger(), "toast_provider")
            channel.setMethodCallHandler(ToastProviderPlugin(registrar))
        }
    }

    override fun onMethodCall(call: MethodCall, result: Result): Unit {
        val context = registrar.context()
        val message = call.argument<String?>("message") ?: throw NullPointerException("参数message不能为null")
        when (call.method) {
            "showShortToast" -> {
                showToast(context, message, Toast.LENGTH_SHORT)
                result.success(null)
            }
            "showLongToast" -> {
                showToast(context, message, Toast.LENGTH_LONG)
                result.success(null)
            }
            "showToast" -> {
                showToast(context, message, call.argument("duration")
                        ?: Toast.LENGTH_SHORT)
                result.success(null)
            }
            else -> result.notImplemented()
        }
    }

    private fun showToast(context: Context, message: String, duration: Int) = Toast.makeText(context, message, duration).show()

}
